package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LYW
 * Date: 2025-05-25
 * Time: 22:01
 */
//wait notify练习
//有三个线程分别只能打印A B C 按照顺序打印ABC 打印10次
public class Demo25 {
    public static void main(String[] args) throws InterruptedException {
        Object locker1 = new Object();
        Object locker2 = new Object();
        Object locker3 = new Object();

        Thread thread1 = new Thread(() -> {
           try {
               for (int i = 0; i < 10; i++) {
                   synchronized (locker1) {
                       locker1.wait();
                   }
                   System.out.print("A");
                   synchronized (locker2) {
                       locker2.notify();
                   }
               }
           }catch (InterruptedException e) {
               throw new RuntimeException();
           }
        });

        Thread thread2 = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    synchronized (locker2) {
                        locker2.wait();
                    }
                    System.out.print("B");
                    synchronized (locker3) {
                        locker3.notify();
                    }
                }
            }catch (InterruptedException e) {
                throw new RuntimeException();
            }
        });

        Thread thread3 = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    synchronized (locker3) {
                        locker3.wait();
                    }
                    System.out.println("C");
                    synchronized (locker1) {
                        locker1.notify();
                    }
                }
            }catch (InterruptedException e) {
                throw new RuntimeException();
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();

        //主线程中先通知依次locker1 上述逻辑从thread1开始执行
        //需要确保都执行到wait 在进行notify的执行 所以要先休眠
        Thread.sleep(1000);
        synchronized (locker1) {
            locker1.notify();
        }
    }
}
